
package BOH.GUI;

import BOH.data.EateryDBConnection;
import java.awt.*;
import java.awt.event.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import javax.swing.event.*;

/**
 * The Back of House System for a
 * small restaurant.
 * 
 * Maeghan Colvin & Jennifer Havemman
 * CSC 289 0B01
 * February 13, 2014
 */
public class EditClockInOutPanel extends JPanel
{
    // Variables
    private JFrame frame;
    private JPanel mainPanel;               // Holds the mainPanel
    private JPanel optionsPanel;            // Holds the optionsPanel
    private JPanel buttonPanel;             // Holds the buttonPanel
    private JPanel tempPanel;               // Holds tempPanel for formatting
    private JLabel employeeIDLabel;         // Holds the employeeID Label   
    private JLabel nameLabel;               // Holds the nameLabel
    private JLabel startingDateLabel;       // Holds the startingDateLabel
    private JLabel startingTimeLabel;       // Holds the startingTimeLabel
    private JLabel endingDateLabel;         // Holds the endingDateLabel
    private JLabel endingTimeLabel;         // Holds the endingTimeLabel
    private JComboBox employeeIDBox;        // Holds the employee ID information
    private JComboBox nameBox;              // Holds the name
    private JSpinner startingDateSpinner;   // Holds starting date
    private JSpinner startingTimeSpinner;   // Holds the starting time
    private JSpinner endingDateSpinner;     // Holds ending date
    private JSpinner endingTimeSpinner;     // Holds the ending time
    private SpinnerDateModel model;         // Holds model of startingDate
    private SpinnerDateModel model2;        // Holds model for ending date
    private SpinnerDateModel model3;        // Holds model for startingTime
    private SpinnerDateModel model4;        // Holds model for startingTime
    private String employeeID = "100";      // Holds the employeeID number
    private String startingDate;            // Holds the startingDate
    private String endingDate;              // Holds the endingDate
    private String startingTime;            // Holds the startingTime
    private String endingTime;              // Holds the endingTime
    private String hourMinuteSecond;        // Holds hourMinuteSecond
    private SimpleDateFormat dateFormat;    // Holds date format
    private SimpleDateFormat militaryTimeFormat;// Holds military time format
    private SimpleDateFormat civilianTimeFormat;// Holds civilian time format
    private String[] employeeIDArray;       // Fills the employeeIDBox
    private String[] nameArray;             // Fills the nameBox
    private String employeeIDSelection;     // Holds the employeeID from comboBox
    private String nameSelection;           // Holds the nameSelection
    private int nameBoxIndex;               // Hold the index to find proper employeeID
    private JButton editButton;             // Edits clock in/out time
    private String sqlStatement;            // Selects the employeeID for combobox
    private String sqlStatement2;           // Selects last, first name for combobox
    private String sqlStatement3;
    
    /**
     * Constructor
     */
    
    public EditClockInOutPanel()
    {
        // Set Look and Feel.
        JFrame.setDefaultLookAndFeelDecorated(true);
        
        // Create and set up the window.
        frame = new JFrame("Edit Clock in/out Time");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        // Build and add mainPanel
        this.buildMainPanel();
        frame.add(mainPanel);
        
        // Add content to the window.
        frame.setSize(300, 400);
        frame.validate();
        
        // Display the window.
        frame.setVisible(true);  
    }
    
    /**
     * The buildMainPanel builds the 
     * mainPanel.
     */
    
    private void buildMainPanel() 
    {
        // Create mainPanel
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // Get optionsPanel
        buildOptionsPanel();
        
        // Get buttonPanel
        buildButtonPanel();
        
        // Add panels
        mainPanel.add(optionsPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    }
    
     /**
     * The buildOptionsPanel builds the 
     * optionsPanel.
     */
    
    private void buildOptionsPanel() 
    {
        // Create optionsPanel
        optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        optionsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // Create optionsPanel
        tempPanel = new JPanel(new GridLayout(12, 0));
        tempPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // Create the JLabels
        employeeIDLabel = new JLabel("Employee ID: ");
        nameLabel = new JLabel("Employee Name: ");
        startingDateLabel = new JLabel("Starting Date: ");
        startingTimeLabel = new JLabel("Starting Time: ");
        endingDateLabel = new JLabel("Ending Date: ");
        endingTimeLabel = new JLabel("Ending Time: ");
        
        // Fill the Arrays for the combo boxes
        employeeIDArray = getEmployeeID();
        nameArray = getEmployeeName();
        
        // Create combo boxes
        employeeIDBox = new JComboBox(employeeIDArray);
        employeeIDBox.setToolTipText("Select employee ID");
        employeeIDBox.addActionListener(new EditClockInOutPanel.EmployeeIDComboBoxListener());
        nameBox = new JComboBox(nameArray);
        nameBox.setToolTipText("Select a name");
        nameBox.addActionListener(new EditClockInOutPanel.NameComboBoxListener());
        
        // Create dates for spinners
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date initDate = calendar.getTime();
        calendar.add(Calendar.YEAR, -100);
        Date earliestDate = calendar.getTime();
        calendar.add(Calendar.YEAR, 200);
        Date latestDate = calendar.getTime();
                
        // Create startingDateSpinner model
        model = new SpinnerDateModel(initDate, //initial value
                               earliestDate, //min
                               latestDate, //max
                               Calendar.YEAR);                //step
        
        // Create endingDateSpinner model
        model2 = new SpinnerDateModel(initDate, //initial value
                               earliestDate, //min
                               latestDate, //max
                               Calendar.YEAR);                //step
        
        // Create startingTimeSpinner model
        civilianTimeFormat = new SimpleDateFormat("hh:mm a");
        militaryTimeFormat = new SimpleDateFormat("HH:mm:ss");
        model3 = new SpinnerDateModel();
        model3.setCalendarField(Calendar.MINUTE);
        
        // Create endingTimeSpinner model
        model4 = new SpinnerDateModel();
        model4.setCalendarField(Calendar.MINUTE);
        
        // Create startingDatespinner
        startingDateSpinner = new JSpinner(model);
        startingDateSpinner.setToolTipText("Select a starting date");
        startingDateSpinner.setEditor(new JSpinner.DateEditor(startingDateSpinner, dateFormat.toPattern()));
        startingDateSpinner.addChangeListener(new EditClockInOutPanel.StartingDateSpinnerListener());
        
        // Create startingTimeSpinner
        startingTimeSpinner = new JSpinner(model3);
        startingTimeSpinner.setToolTipText("Select a starting time");
        startingTimeSpinner.setEditor(new JSpinner.DateEditor(startingTimeSpinner, civilianTimeFormat.toPattern()));
        startingTimeSpinner.addChangeListener(new EditClockInOutPanel.StartingTimeSpinnerListener());
        
        // Create endingDateSpinner
        endingDateSpinner = new JSpinner(model2);
        endingDateSpinner.setToolTipText("Select an ending date");
        endingDateSpinner.setEditor(new JSpinner.DateEditor(endingDateSpinner, dateFormat.toPattern()));
        endingDateSpinner.addChangeListener(new EditClockInOutPanel.EndingDateSpinnerListener());
        
        // Create endingTimeSpinner
        endingTimeSpinner = new JSpinner(model4);
        endingTimeSpinner.setToolTipText("Select an ending time");
        endingTimeSpinner.setEditor(new JSpinner.DateEditor(endingTimeSpinner, civilianTimeFormat.toPattern()));
        endingTimeSpinner.addChangeListener(new EditClockInOutPanel.EndingTimeSpinnerListener());
        
        // Add components to panel
        tempPanel.add(employeeIDLabel);
        tempPanel.add(employeeIDBox);
        tempPanel.add(nameLabel);
        tempPanel.add(nameBox);
        tempPanel.add(startingDateLabel);
        tempPanel.add(startingDateSpinner);
        tempPanel.add(startingTimeLabel);
        tempPanel.add(startingTimeSpinner);
        tempPanel.add(endingDateLabel);
        tempPanel.add(endingDateSpinner);
        tempPanel.add(endingTimeLabel);
        tempPanel.add(endingTimeSpinner);
        optionsPanel.add(tempPanel);
    }
    
    /**
     * The buildButtonPanel builds the 
     * buttonPanel.
     */
    
    private void buildButtonPanel() 
    {
        // Create buttonPanel
        buttonPanel = new JPanel(new BorderLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // Create button
        editButton = new JButton("Edit");
        editButton.setMnemonic(KeyEvent.VK_E);
        editButton.addActionListener(new EditClockInOutPanel.EditButtonActionListener());
        
        // Add components to the buttonPanel
        buttonPanel.add(editButton, BorderLayout.CENTER);
    }
    
    /**
     * The getEmployeeIDBoxSelection method returns
     * the selected item in the comboBox
     * @param e 
     * @return
     */
    
    public String getEmployeeIDBoxSelection()
    {
        // Get the selected option
        employeeIDSelection = (String) employeeIDBox.getSelectedItem();
        return employeeIDSelection;
    }
    
    /**
     * The getNamesBoxSelection method returns
     * the selected item in the comboBox
     * @param e 
     * @return 
     */
    
    public int getNamesBoxSelection()
    {
        // Call the employeeIDArray
        employeeIDArray = getEmployeeID();
        
        // Get the selected option
        nameSelection = (String) nameBox.getSelectedItem();
        
        // Get the selected index
        nameBoxIndex = java.util.Arrays.asList(nameArray).indexOf(nameSelection);
        
        // Return
        return nameBoxIndex;
    }
    
    /**
     * The getEmployeeID method gets the names
     * to fill the employeeID combo box.
     * @return
     */
    
    public String[] getEmployeeID()
    {
        sqlStatement = "SELECT EmployeeID " +
                       "FROM Employee";
        
        employeeIDArray = EateryDBConnection.getData(sqlStatement);
        
        // Return
        return employeeIDArray;
    }
    
    /**
     * The getEmployeeNAme method gets names
     * to fill the Name combo boxes.
     * @return
     */
    
    public String[] getEmployeeName()
    {
        sqlStatement2 = "SELECT LastName || ', ' || FirstName " +
                        "FROM Employee";
        
        nameArray = EateryDBConnection.getData(sqlStatement2);
        
        // Return
        return nameArray;
    }
    
    /**
     * The getHoursWorked method gets 
     * the hours worked for an employee.
     * @return
     */
    
    public String getHoursWorked()
    {
        // Variables
        String timeIn = startingDate + " " + startingTime;
        String timeOut = endingDate + " " + endingTime;
        
        // Create date format
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // Convert the string dates to dateformat.
        try
        {
            // Parse the strings into the date format and substract
            Date date1 = dateTimeFormat.parse(timeIn);  
            Date date2 = dateTimeFormat.parse(timeOut);
            long newTime = Math.abs(date1.getTime() - date2.getTime());
            
            // Convert milliseconds to HH:mm:ss and update database
            hourMinuteSecond = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(newTime),
            TimeUnit.MILLISECONDS.toMinutes(newTime) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(newTime)),
            TimeUnit.MILLISECONDS.toSeconds(newTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(newTime)));
            sqlStatement3 = "UPDATE ClockInOut " +
                            "SET ClockIn = '" + timeIn + "', " +
                            "ClockOut = '" + timeOut + "', " +
                            "TotalTime = '" + hourMinuteSecond + "' " +
                            "WHERE EmployeeID = " + employeeID + " " +
                            "AND ClockOut = '" + endingDate + "%' ";
            EateryDBConnection.updateDatabase(sqlStatement3);
            JOptionPane.showMessageDialog(null, "Clock in/out time updated.");
            System.out.println(sqlStatement3);
        }
        catch (ParseException e) 
        {
	}
        // Return
        return hourMinuteSecond;
    }
    
    /*
     * The EmployeeIDComboBoxListener is used to collect
     * the employee ID or all when nothing is selected.
     */
    
    private class EmployeeIDComboBoxListener implements ActionListener 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            employeeIDSelection = getEmployeeIDBoxSelection();
            employeeID = employeeIDSelection;
        }
    }
    
    /*
     * The NameComboBoxListener is used to collect
     * the employee name that is selected and
     * matches it with the proper employeeID number.
     */
    
    private class NameComboBoxListener implements ActionListener 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            nameBoxIndex = getNamesBoxSelection();
            nameSelection = employeeIDArray[nameBoxIndex];
            employeeID = nameSelection;
        }
    }
    
    /*
     * The StartingDateSpinnerListener is used to 
     * retrieve the clock in date for pay roll.
     */
    
    private class StartingDateSpinnerListener implements ChangeListener 
    {
        @Override
        public void stateChanged(ChangeEvent e) 
        {

                startingDateSpinner = (JSpinner)(e.getSource());
                startingDate = dateFormat.format(startingDateSpinner.getValue());
        }
    }
    
    /*
     * The StartingTimeSpinnerListener is used to 
     * retrieve the clock in time for pay roll.
     */
    
    private class StartingTimeSpinnerListener implements ChangeListener 
    {
        @Override
        public void stateChanged(ChangeEvent e) 
        {
            startingTimeSpinner = (JSpinner)(e.getSource());
            startingTime = militaryTimeFormat.format(startingTimeSpinner.getValue());
        }
    }
    
    /*
     * The EndingDateSpinnerListener is used to 
     * retrieve the clock out date for pay roll.
     */
    
    private class EndingDateSpinnerListener implements ChangeListener 
    {
        @Override
        public void stateChanged(ChangeEvent e) 
        {

                endingDateSpinner = (JSpinner)(e.getSource());
                endingDate = dateFormat.format(endingDateSpinner.getValue());
        }
    }
    
    /*
     * The EndingTimeSpinnerListener is used to 
     * retrieve the clock out time for pay roll.
     */
    
    private class EndingTimeSpinnerListener implements ChangeListener 
    {
        @Override
        public void stateChanged(ChangeEvent e) 
        {

                endingTimeSpinner = (JSpinner)(e.getSource());
                endingTime = militaryTimeFormat.format(endingTimeSpinner.getValue());
        }
    }
    
    /*
     * The EditButtonActionListener is used to
     * view the payroll information.
     */
    
    private class EditButtonActionListener implements ActionListener 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            hourMinuteSecond = getHoursWorked();
        }
    }
}
